﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.IO.Compression;

namespace NLBS.Utility
{
    /// <summary>
    /// GZip辅助类
    /// </summary>
   public class GZipHelper
    {
        public static bool IsGZipSupported()
        {
            string AcceptEncoding = HttpContext.Current.Request.Headers["Accept-Encoding"];
            //检测headers中的Accept-Encoding
            if (!string.IsNullOrEmpty(AcceptEncoding) && (AcceptEncoding.Contains("gzip") || AcceptEncoding.Contains("deflate")))
                //如果Accept-Encoding含有gzip或deflate，表示浏览器支持这种压缩。
                return true;
            return false;
        }

        
        public static void GZipEncodePage()
        {
            if (IsGZipSupported())//如果支持压缩
            {
                HttpResponse Response = HttpContext.Current.Response;
                string AcceptEncoding = HttpContext.Current.Request.Headers["Accept-Encoding"];
                if (AcceptEncoding.Contains("gzip"))//如果支持gzip，就使用gzip的压缩方式
                {

                    Response.Filter = new GZipStream(Response.Filter, CompressionMode.Compress);
                    //只需要把HttpResponse.Filter变成GZipStream就行了。
                    Response.AppendHeader("Content-Encoding", "gzip");//添加gzip到浏览器header
                }
                else//采用defalte的压缩方式，另一种内置的压缩方式。
                {
                    Response.Filter = new DeflateStream(Response.Filter,
                    CompressionMode.Compress);
                    //同样原理
                    Response.AppendHeader("Content-Encoding", "deflate");
                    //添加deflate到浏览器header
                }
            }
        }
    }
}
